//
//  HPCardORRecordViewController.m
//  HPZZTong
//
//  Created by handpay on 14-4-4.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPCardORRecordViewController.h"
#import "ZZTongUtility.h"
#import "HPDateTimeListView.h"
#import "HPTransRecordView.h"
#import "BankCardNetService.h"
#import <HandPaySwiperModule/HandPaySwiperModule.h>

#define kCellBankLogImageViewTag    10005
#define kCellCardNoLabelTag         10006
#define kCellDeleteBgViewTag        10008
#define kCellDeleteButtonTag        10010


@interface HPCardORRecordViewController ()
{
    IBOutlet UIImageView *tabBgImageView;
    IBOutlet UIButton *recordButton;
    IBOutlet UIButton *cardButton;
    HPTransRecordView *recordBgView;
    UIView* cardBgView;
    UIView* curProgressView;    //卡包当前已刷卡view
    UILabel* curCardLabel;      //当前已刷／可刷卡
    NSUInteger progressWidth;   //卡包可刷卡总长度
    
    UITableView* cardPackTableView;
    
    BOOL deleting;
    
    NSMutableArray* cardPackArray;
}
@property(nonatomic, retain)UIImage* tabLeftImage;
@property(nonatomic, retain)UIImage* tabRightImage;
@property (nonatomic, retain) NSMutableArray *editingCellArray;

- (IBAction)tabButtonClick:(id)sender;

@end

@implementation HPCardORRecordViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self createItem];
    }
    return self;
}
- (void)createItem{
    self.tabRightImage = [UIImage imageNamed:@"tab1.png"];
    self.tabLeftImage = [UIImage imageNamed:@"tab2.png"];
    
    CGRect frame = CGRectMake(0, 35, ScreenWidth, 395);
    if (HP_Device_iPhone5) {
        frame.size.height += IPHONE5_ADD_HEIGHT;
    }
    
    [self createCardPackView:frame];
    
    recordBgView = [[HPTransRecordView alloc]initWithFrame:frame];
    recordBgView.backgroundColor = [UIColor whiteColor];
    recordBgView.hidden = YES;
    
    [self.view addSubview:recordBgView];
}
- (void)createCardPackView:(CGRect)frame{
    cardBgView = [[UIView alloc]initWithFrame:frame];
    cardBgView.backgroundColor = [UIColor whiteColor];
    
    progressWidth = 300;
    int h = 30;
    int left = 10;
    int top = 10;
    UIView* progressView = [[UIView alloc]initWithFrame:CGRectMake(left, top, progressWidth, h)];
    progressView.backgroundColor = kLineFontColor;
    progressView.layer.cornerRadius = 15.0;
    progressView.layer.borderColor = kLineFontColor.CGColor;
    progressView.layer.borderWidth = 1;
    [cardBgView addSubview:progressView];
    [progressView release];
    
    int space = 3;
    top += space;
    
    
    curProgressView = [[UIView alloc]initWithFrame:CGRectMake(left + space, top, progressWidth - 2 * space, h - 2* space)];
    curProgressView.backgroundColor = kTitleFontColor;
    curProgressView.layer.cornerRadius = 12.0;
    curProgressView.layer.borderWidth = 1;
    curProgressView.layer.borderColor = kTitleFontColor.CGColor;
    [cardBgView addSubview:curProgressView];
    
    CGRect labelFrame = curProgressView.frame;
    labelFrame.origin.x -= 6;
    labelFrame.size.width += 6;
    
    curCardLabel = [[UILabel alloc]initWithFrame:labelFrame];
    curCardLabel.backgroundColor = [UIColor clearColor];
    curCardLabel.textAlignment = NSTextAlignmentRight;
    curCardLabel.textColor = [UIColor whiteColor];
    curCardLabel.font = kSecondSmallFont;
    [cardBgView addSubview:curCardLabel];
    
    top += h + 15;
    h = 40;
    UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(left, top, progressWidth, h)];
    label.text = @"为了保证刷卡器的私人安全，每个刷卡器刷卡容量是10张，每日最多可以删除5张";
    label.textColor = kNormalFontColor;
    label.numberOfLines = 0;
    label.font = kSecondSmallFont;
    [cardBgView addSubview:label];
    [label release];
    
    top += h + 10;
    cardPackTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, top, ScreenWidth, cardBgView.frame.size.height - top - 10) style:UITableViewStylePlain];
    cardPackTableView.backgroundColor = [UIColor clearColor];
    cardPackTableView.dataSource = self;
    cardPackTableView.delegate = self;
    [cardBgView addSubview:cardPackTableView];
    
    [self.view addSubview:cardBgView];
}

- (void)viewDidLoad
{
    self.title = @"快速转账";
    [super viewDidLoad];
    
    deleting = NO;
    
    self.editingCellArray = [NSMutableArray array];
    
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
    [b setFrame:CGRectMake(0, 0, 44, 44)];
    [b setContentEdgeInsets:UIEdgeInsetsMake(10, 20, 10, 0)];
    [b setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    [b addTarget:self action:@selector(doEdit) forControlEvents:UIControlEventTouchUpInside];
    [b setImage:[UIImage imageNamed:@"queren.png"] forState:UIControlStateSelected];
    self.rightButton = b;
    self.rightButton.hidden = YES;
    [super setRightButton:b];
    
}
- (void)doEdit{
    [self setDeleting:!deleting animate:YES];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [ZZT_UIENG showNetWaiting];
    [self queryCardPack];
}

-(void)queryCardPack
{
    id<HPSwipeServiceProtocal> service = [HPSwiperContext sharedInstance].avaliableService;
//   [service selectSwiperAndGetCsn:^(HPSwiperResult *swiperResult) {
//       [self doQueryCardPack];
//   } isShow:NO];
}

- (void)doQueryCardPack{
    [BankCardNetService doGetBankCardList:^(NSDictionary *resultDic) {
        NSString* respCode = [resultDic objectForKey:@"responseCode"];
        if ([respCode isEqualToString:SUCCESS_CUP]) {
            NSArray* array = [resultDic objectForKey:@"cardList"];
            if (array) {
                cardPackArray = [[NSMutableArray alloc]initWithArray:array];
                [self updateCardNum];
                [cardPackTableView reloadData];
                [HPUIENG removeWaiting];
                return;
            }
        }
        [HPUIENG showAlert:@"数据加载失败，请重试"];
    }];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    [cardButton release];
    [recordButton release];
    [tabBgImageView release];
    self.editingCellArray = nil;
    self.tabLeftImage = nil;
    self.tabRightImage = nil;
    if (cardBgView) {
        [cardBgView release];
        cardBgView = nil;
    }

    if (curCardLabel) {
        [curCardLabel release];
        curCardLabel = nil;
    }
    if (curProgressView) {
        [curProgressView release];
        curProgressView = nil;
    }
    if (cardPackTableView) {
        [cardPackTableView release];
        cardPackTableView = nil;
    }
    if (cardPackArray) {
        [cardPackArray release];
        cardPackArray = nil;
    }
    if (recordBgView) {
        [recordBgView release];
        recordBgView = nil;
    }
    [super dealloc];
}
- (void)viewDidUnload {
    [cardButton release];
    cardButton = nil;
    [recordButton release];
    recordButton = nil;
    [tabBgImageView release];
    tabBgImageView = nil;
    if (cardBgView) {
        [cardBgView release];
        cardBgView = nil;
    }

    if (curCardLabel) {
        [curCardLabel release];
        curCardLabel = nil;
    }
    if (curProgressView) {
        [curProgressView release];
        curProgressView = nil;
    }
    if (cardPackTableView) {
        [cardPackTableView release];
        cardPackTableView = nil;
    }
    if (cardPackArray) {
        [cardPackArray release];
        cardPackArray = nil;
    }
    [recordBgView release];
    recordBgView = nil;
    [super viewDidUnload];
}
- (IBAction)tabButtonClick:(id)sender {
    UIButton* button = (UIButton*)sender;
    if (button == cardButton) {
        tabBgImageView.image = self.tabLeftImage;
        cardBgView.hidden = NO;
        recordBgView.hidden = YES;
        
        [ZZT_UIENG showNetWaiting];
        [self queryCardPack];
    }else{
        tabBgImageView.image = self.tabRightImage;
        cardBgView.hidden = YES;
        recordBgView.hidden = NO;
        self.rightButton.hidden = YES;
        recordBgView.appCode = [self.screenData objectForKey:@"appCode"];
    }
}

#pragma mark - 私有方法

/**
 * 隐藏所有的删除单元格view
 */
- (void) hideAllDeleteBgViewAnimate:(BOOL)animate
{
    for (NSIndexPath *indexPath in self.editingCellArray) {
        UITableViewCell *cell = [cardPackTableView cellForRowAtIndexPath:indexPath];
        
        UIView *deleteBgView = (UIView *)[cell viewWithTag:kCellDeleteBgViewTag];
        UIButton *deleteButton = (UIButton *)[deleteBgView viewWithTag:kCellDeleteButtonTag];
        
        
        CGRect deleteButtonFrame = deleteButton.frame;
        
        // 先显示
        deleteButtonFrame.origin.x = 250;
        
        [deleteButton setFrame:deleteButtonFrame];
        
        // 再隐藏
        deleteButtonFrame.origin.x = ScreenWidth;
        if (animate) {
            [UIView animateWithDuration:.25 animations:^{
                [deleteButton setFrame:deleteButtonFrame];
            } completion:^(BOOL finished) {
                if (finished) {
                    [deleteBgView setHidden:YES];
                }
            }];
        } else {
            [deleteButton setFrame:deleteButtonFrame];
            [deleteBgView setHidden:YES];
        }
    }
    [self.editingCellArray removeAllObjects];
}

/**
 * 隐藏指定的删除单元格view
 */
- (void) hideDeleteBgView:(UIView *)deleteBgView
{
    UIButton *deleteButton = (UIButton *)[deleteBgView viewWithTag:kCellDeleteButtonTag];
    
    CGRect deleteButtonFrame = deleteButton.frame;
    
    deleteButtonFrame.origin.x = ScreenWidth;
    
    [deleteButton setFrame:deleteButtonFrame];
    [deleteBgView setHidden:YES];
}

/**
 * 显示指定的删除单元格view
 */
- (void) showDeleteBgView:(UIView *)deleteBgView animate:(BOOL)animate
{
    UITableViewCell *cell = [self getTableViewCell:deleteBgView];
    UIButton *deleteButton = (UIButton *)[deleteBgView viewWithTag:kCellDeleteButtonTag];
    
    CGRect deleteButtonFrame = deleteButton.frame;
    
    // 先隐藏
    deleteButtonFrame.origin.x = ScreenWidth;
    
    [deleteButton setFrame:deleteButtonFrame];
    
    // 再显示
    deleteButtonFrame.origin.x = 250;
    
    [deleteBgView setHidden:NO];
    if (animate) {
        [UIView animateWithDuration:.25 animations:^{
            [deleteButton setFrame:deleteButtonFrame];
        } completion:^(BOOL finished) {
            if (finished) {
                [self.editingCellArray addObject:[cardPackTableView indexPathForCell:cell]];
            }
        }];
    } else {
        [deleteButton setFrame:deleteButtonFrame];
    }
}

/**
 * 滑动cell事件
 */
- (void) swipe:(UISwipeGestureRecognizer *)recognizer
{
    
    UITableViewCell *cell = (UITableViewCell *)recognizer.view;
    [cell setSelected:NO];
    
    UIView *deleteBgView = (UIView *)[cell viewWithTag:kCellDeleteBgViewTag];
    
    BOOL editing = NO;
    
    NSIndexPath *indexPath = [cardPackTableView indexPathForCell:cell];
    for (NSIndexPath *ip in self.editingCellArray) {
        if (ip.section == indexPath.section && ip.row == indexPath.row) {
            editing = YES;
        }
    }
    [self hideAllDeleteBgViewAnimate:YES];
    if (!editing) {
        [self showDeleteBgView:deleteBgView animate:YES];
    }
}
/**
 * 点击删除背景
 */
- (void) touchDeleteBgButton:(UIButton *)sender
{
    [self hideAllDeleteBgViewAnimate:YES];
}

- (void)sendDeleteRequest:(NSUInteger)index{
    ZZTongClientEngine* zztEngine = [ZZTongClientEngine sharedInstance];
    
    [zztEngine.uiEngine showNetWaiting];
    
    [BankCardNetService doDeleteBankCard:[cardPackArray objectAtIndex:index] complete:^(NSDictionary *resultDic) {
        NSString* respCode = [resultDic objectForKey:@"responseCode"];
        if ([respCode isEqualToString:SUCCESS_CUP]) {
            [HPUIENG removeWaiting];
            NSMutableArray *indexs = nil;
            indexs = [NSMutableArray arrayWithObjects:[NSNumber numberWithUnsignedInteger:index], nil];
            NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:indexs.count];
            for (NSNumber *index_ in indexs) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[index_ unsignedIntValue] inSection:0];
                [indexPaths addObject:indexPath];
                [cardPackArray removeObjectAtIndex:[index_ unsignedIntValue]];
            }
            [cardPackTableView beginUpdates];
            [cardPackTableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
            [cardPackTableView endUpdates];
            
            [self updateCardNum];
        }else if([respCode isEqualToString:@"XU"]){
            [HPUIENG showAlert:@"每日最多删除5张银行卡"];
            [self setDeleting:NO animate:YES];
        }else{
            [HPUIENG showAlert:@"银行卡删除失败，请重试"];
        }
    }];
}
/**
 * 点击删除按钮
 */
- (void) touchDeleteButton:(UIButton *)sender
{
    
    UITableViewCell *cell = [self getTableViewCell:sender];
    NSIndexPath *indexPath = [cardPackTableView indexPathForCell:cell];
    NSMutableArray* array = [[NSMutableArray alloc]initWithArray:self.editingCellArray];
    for (NSIndexPath *ip in array) {
        if (ip.section == indexPath.section && ip.row == indexPath.row) {
            [self.editingCellArray removeObject:ip];
        }
    }
    [array release];
    [self hideDeleteBgView:[cell viewWithTag:kCellDeleteBgViewTag]];
    [self sendDeleteRequest:indexPath.row];
}
- (void)updateCardNum{
    
    NSUInteger count = 0;
    if (cardPackArray) {
        count = cardPackArray.count;
    }
    
    self.rightButton.hidden = count > 0 ? NO :YES;
    
    CGRect frame = cardPackTableView.frame;
    NSUInteger h = count * kCellHeight;
   curCardLabel.text = [NSString stringWithFormat:@"%d/10",(int)count];
    if (count == 0) {
        curProgressView.hidden = count > 0 ? NO :YES;
        count = 1;
    }
    if (h < (cardBgView.frame.size.height - frame.origin.y - 10)) {
        frame.size.height = h;
        cardPackTableView.scrollEnabled = NO;
    }
    cardPackTableView.frame = frame;
    
    h = (float)(count * progressWidth)/ 10 ;
    frame = curProgressView.frame;
    frame.size.width = h;
    curProgressView.frame = frame;
    
    frame.size.width += 6;
    frame.origin.x -= 6;
    curCardLabel.frame = frame;
    
    
}
- (UITableViewCell*)getTableViewCell:(UIView*)tarView{
    UIView* tempCell = tarView.superview;
    while (tempCell) {
        if ([tempCell isKindOfClass:[UITableViewCell class]]) {
            return (UITableViewCell*)tempCell;
        }
        
        tempCell = tempCell.superview;
    }
    
    return nil;
}

- (void) setDeleting:(BOOL)deleting_ animate:(BOOL)animate
{
    self.rightButton.selected = deleting_;
    if (!deleting_) {
        [self hideAllDeleteBgViewAnimate:YES];
    } else {
        UITableViewCell *cell;
        int section = 0;
        for (int j = 0; j < [cardPackTableView numberOfRowsInSection:section]; j ++) {
            cell = [cardPackTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:j inSection:section]];
            if (cell == nil) {
                // 没展示出来的cell
                [self.editingCellArray addObject:[NSIndexPath indexPathForRow:j inSection:section]];
                continue;
            }
            [cell setSelected:NO];
            
            UIView *deleteBgView = (UIView *)[cell viewWithTag:kCellDeleteBgViewTag];
            
            if (deleteBgView == nil) {
                continue;
            }
            
            NSIndexPath *indexPath = [cardPackTableView indexPathForCell:cell];
            
            BOOL editing = NO;
            for (NSIndexPath *ip in self.editingCellArray) {
                if (ip.section == indexPath.section && ip.row == indexPath.row) {
                    editing = YES;
                }
            }
            if (!editing) {
                [self showDeleteBgView:deleteBgView animate:YES];
            }
        }
    }
    deleting = deleting_;
}
#pragma mark - table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kCellHeight;
}

#pragma mark - Table view data source

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (cardPackArray && cardPackArray.count != 0) {
        return cardPackArray.count;
    }
    return 0;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        [cell setAutoresizesSubviews:NO];
        cell.backgroundColor = [UIColor clearColor];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        UISwipeGestureRecognizer *swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
        [swipeGestureRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight];
        [cell addGestureRecognizer:swipeGestureRecognizer];
        [swipeGestureRecognizer release];
        
        // 银行logo
        UIImageView *bankLogoImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cmbc.png"]];
        [bankLogoImageView setTag:kCellBankLogImageViewTag];
        [bankLogoImageView setFrame:CGRectMake(25, 12, 25, 25)];
        [cell addSubview:bankLogoImageView];
        [bankLogoImageView release];
        
        // 卡号
        UILabel *cardNoLabel = [[UILabel alloc] initWithFrame:CGRectMake(75, 0, 175, kCellHeight)];
        [cardNoLabel setTag:kCellCardNoLabelTag];
        [cardNoLabel setBackgroundColor:[UIColor clearColor]];
        [cardNoLabel setFont:kNormalFont];
        [cardNoLabel setMinimumScaleFactor:14];
        [cardNoLabel setTextColor:kNormalFontColor];
        [cell addSubview:cardNoLabel];
        [cardNoLabel release];
        
        
        UIView *deleteBgView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, cell.frame.size.width, cell.frame.size.height)];
        [deleteBgView setTag:kCellDeleteBgViewTag];
        [deleteBgView setBackgroundColor:[UIColor clearColor]];
        
        UIButton *deleteBgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [deleteBgButton setExclusiveTouch:YES];
        [deleteBgButton setBackgroundColor:[UIColor clearColor]];
        [deleteBgButton addTarget:self action:@selector(touchDeleteBgButton:) forControlEvents:UIControlEventTouchUpInside];
        [deleteBgButton setFrame:deleteBgView.frame];
        [deleteBgView addSubview:deleteBgButton];
        
        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [deleteButton setExclusiveTouch:YES];
        [deleteButton setTag:kCellDeleteButtonTag];
        [deleteButton setImage:[UIImage imageNamed:@"clear.png"] forState:UIControlStateNormal];
        [deleteButton setImageEdgeInsets:UIEdgeInsetsMake(14, 14, 14, 14)];
        [deleteButton addTarget:self action:@selector(touchDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
        [deleteButton setFrame:CGRectMake(ScreenWidth, 0, kCellHeight, kCellHeight)];
        [deleteBgView addSubview:deleteButton];
        
        [deleteBgView setHidden:YES];
        [cell addSubview:deleteBgView];
        [deleteBgView release];
    }
    
    
    UIView *deleteBgView = (UIView *)[cell viewWithTag:kCellDeleteBgViewTag];
    [self hideDeleteBgView:deleteBgView];
    for (NSIndexPath *ip in self.editingCellArray) {
        if (ip.section == indexPath.section && ip.row == indexPath.row) {
            [self showDeleteBgView:deleteBgView animate:NO];
        }
    }
    NSString* cardNo = (NSString*)[cardPackArray objectAtIndex:indexPath.row];
    UILabel *cardNoLabel = (UILabel *)[cell viewWithTag:kCellCardNoLabelTag];
    
    
    [cardNoLabel setText:[Utility encryptCardID:cardNo]];
    
    UIImageView* imageView = (UIImageView*)[cell viewWithTag:kCellBankLogImageViewTag];
    NSString* imageName = [ZZTUtility getBankLogo:cardNo];
    imageView.image = [UIImage imageNamed:imageName];
    return cell;

}


@end
